vim.g.mapleader = ' '
vim.g.neotree_width = 20

-- 常用快捷键
local map = vim.keymap.set
map('n', '<leader>t', ':ToggleTerm<CR>', { silent = true }) -- 文件树开关
map('n', '<leader>e', 
    function()
        local tn = vim.api.nvim_get_current_tabpage()
        local tree_win_handle = nil

        vim.cmd("Neotree toggle")
        for _, window_handle in ipairs(vim.api.nvim_tabpage_list_wins(tn)) do
            local buffer_handle = vim.api.nvim_win_get_buf(window_handle)
            local buf_name = vim.fn.bufname(buffer_handle)
            if string.find(buf_name, "^neo%-tree filesystem %[%d+%]$") then              
                tree_win_handle = window_handle
                break
            end
        end
        if tree_win_handle == nil then
            -- Did not find window for neo-tree, could not reset size.
            return
        end
        if vim.api.nvim_win_get_width(tree_win_handle) > 0 then
            -- Reset neo-tree window size to proper value.
            vim.api.nvim_win_set_width(tree_win_handle, vim.g.neotree_width)
            return
        end
    end,
    { silent = true }
)     -- 终端开关
map('n', '<leader>f', ':Telescope find_files<CR>')             -- 文件搜索

-- 设置窗口宽度调整快捷键
map('n', '<A-,>', ':vertical resize -5<CR>', { silent = true })

map('n', '<A-.>', ':vertical resize +5<CR>', { silent = true })

-- 设置窗口高度调整快捷键
map('n', '<A-<>', ':resize -2<CR>', { silent = true })

map('n', '<A->>', ':resize +2<CR>', { silent = true })

map('n', '<A-f>', ':Telescope live_grep<CR>', { silent = true })

map('n', '<leader>lg', function()
    Snacks.lazygit.open()
end, { silent = true })

-- 函数跳转快捷键
map('n', '<leader>gd', function()
    vim.lsp.buf.definition()
end, { silent = true })

map('n', '<leader>gD', function()
    vim.lsp.buf.declaration()
end, { silent = true })

-- 符号重命名快捷键
map('n', '<leader>rn', function()
    vim.lsp.buf.rename()
end, { silent = true })

-- 函数折叠快捷键
map('n', '<leader>ff', function()
    vim.cmd("set foldmethod=expr")
    vim.cmd("set foldexpr=nvim_treesitter#foldexpr()")
    vim.cmd("%foldopen")
end, { silent = true })

map('n', '<leader>za', function()
    vim.cmd("%foldclose")
end, { silent = true })

-- 代码格式化快捷键
map('n', '<S-F>', function()
    require("conform").format()
end, { silent = true })

-- map('n', '<leader>dd', function()
--     vim.diagnostic.setloclist()
-- end, { silent = true })


-- 设置退出终端模式快捷键
map('t', '<esc>', '<C-\\><C-n>', { silent = true })

-- 关闭当前Buffer并切换到前一个Buffer
vim.keymap.set('n', '<A-c>', function()
    local buffer_id = vim.fn.bufnr()
    vim.cmd 'BufferLineCyclePrev'
    vim.cmd('bdelete ' .. buffer_id)
end, { desc = '关闭当前Buffer并切换到前一个' })

-- 关闭当前Buffer并切换到后一个Buffer
vim.keymap.set('n', '<A-C>', function()
    local buffer_id = vim.fn.bufnr()
    vim.cmd 'BufferLineCycleNext'
    vim.cmd('bdelete ' .. buffer_id)
end, { desc = '关闭当前Buffer并切换到后一个' })
